const models = require('../db')
const express = require('express')
const router = express.Router()
const mysql = require('mysql')
const $sql = require('../sqlMap')
// 连接数据库
const conn = mysql.createConnection(models.mysql)
conn.connect()
const jsonWrite = function (res, ret) {
  if (typeof ret === 'undefined') {
    res.json({
      code: '1', msg: '操作失败'
    })
  } else {
    res.json(
      ret
    )
  }
}

// 接口：查询全部
router.post('/goods', (req, res) => {
  const sql = $sql.HomeGoods.goodsSort
  const params = req.body
  console.log('goods接口参数--',params)
  conn.query(sql, [params.type,params.page], function (err, result) {
    console.log('查询语句==',sql)
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWrite(res, result)
    }
  })
});
// 接口：获取商品详情信息
router.post('/goodsiteminfo', (req, res) => {
  const sql = $sql.GoodsItem.itemDetial
  const params = req.body
  // console.log('goodsitem接口参数--',params)
  conn.query(sql, [params.id], function (err, result) {
    // console.log('查询语句==',sql)
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWrite(res, result)
    }
  })
})
// 接口：添加商品到购物车
router.post('/addcart', (req, res) => {
  const sql = $sql.GoodsInsert.addCart
  const params = req.body
  console.log('addcart接口参数--',params)
  conn.query(sql, [params.gid,params.userid], function (err, result) {
    // console.log('查询语句==',sql)
    if (err) {
      console.log(err)
    }
    if (result.affectedRows >0) {
      console.log('添加成功==')
      return result;
    }
  })
})
// 接口：获取购物车商品
router.get('/mycartlist', (req, res) => {
  const sql = $sql.GoodsItem.cartList
  // console.log(req)
  conn.query(sql, function (err, result) {
    // console.log('接口：获取购物车商品==',sql)
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWrite(res, result)
    }
  })
})

module.exports = router